package com.example.gulimallproduct.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.example.common.utils.R;
import com.example.gulimallproduct.entity.CategoryBrandRelationEntity;
import com.example.gulimallproduct.request.SaveCategoryRequest;
import com.example.gulimallproduct.response.SelectCategoryListWithTreeResponse;
import com.example.gulimallproduct.service.CategoryBrandRelationService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.common.utils.PageUtils;
import com.example.common.utils.Query;

import com.example.gulimallproduct.dao.CategoryDao;
import com.example.gulimallproduct.entity.CategoryEntity;
import com.example.gulimallproduct.service.CategoryService;
import org.springframework.transaction.annotation.Transactional;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {
    @Autowired
    private CategoryBrandRelationService categoryBrandRelationService;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<>()
        );

        return new PageUtils(page);
    }



    @Override
    public List<SelectCategoryListWithTreeResponse> SelectCategoryListWithTree() {
        List<SelectCategoryListWithTreeResponse> categoryList = new ArrayList<>();
        List<CategoryEntity> categoryEntities = list();
        List<CategoryEntity> level1Categories = lambdaQuery().eq(CategoryEntity::getCatLevel, 1).list();

        if(CollectionUtil.isNotEmpty(level1Categories)){
            for (CategoryEntity level1Category : level1Categories) {
                SelectCategoryListWithTreeResponse response = new SelectCategoryListWithTreeResponse();
                BeanUtils.copyProperties(level1Category, response);
                if (response.getSort() == null) {
                    response.setSort(0);
                }
                queryChildren(response, categoryEntities);
                categoryList.add(response);
            }
        }
        if(CollectionUtil.isNotEmpty(categoryList)){
            categoryList.sort(Comparator.comparingInt(SelectCategoryListWithTreeResponse::getSort));
        }


        return categoryList;

    }

    @Override
    @Transactional
    public R delCategoryByIds(Long[] catIds) {
        List<Long> catIdList = Arrays.stream(catIds).toList();
        for (Long catId : catIdList) {
            long associationCount = categoryBrandRelationService.lambdaQuery().eq(CategoryBrandRelationEntity::getCatelogId, catId).count();
            if(associationCount > 0){
                return R.error("分类下关联了品牌，不能删除");
            }
            List<CategoryEntity> childList = lambdaQuery()
                    .select(CategoryEntity::getCatId)
                    .eq(CategoryEntity::getParentCid, catId)
                    .list();
            if(CollectionUtil.isNotEmpty( childList)){
                for (CategoryEntity categoryEntity : childList) {
                    if(!catIdList.contains(categoryEntity.getCatId())){
                        return R.error("分类下关联了子分类，不能删除");
                    }
                }
            }
        }
        if(removeByIds(catIdList)){
            return R.ok();
        }
        return R.error("删除失败");
    }

    @Override
    public R saveCategory(SaveCategoryRequest saveCategoryRequest) {
        CategoryEntity categoryEntity = new CategoryEntity();
        BeanUtils.copyProperties(saveCategoryRequest, categoryEntity);
        categoryEntity.setShowStatus(1);
        categoryEntity.setSort(0);
        categoryEntity.setProductCount(0);
        save(categoryEntity);
        return R.ok();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R updateCategory(CategoryEntity category) {
        updateById(category);
        categoryBrandRelationService.lambdaUpdate()
                .eq(CategoryBrandRelationEntity::getCatelogId, category.getCatId())
                .set(CategoryBrandRelationEntity::getCatelogName, category.getName())
                .update();
        return R.ok();
    }

    /**
     * 递归查询树形分类
     * @param parentCategory 父分类
     * @param categoryEntities 所有分类
     */
    private void queryChildren(SelectCategoryListWithTreeResponse parentCategory, List<CategoryEntity> categoryEntities) {
        List<SelectCategoryListWithTreeResponse> children = new ArrayList<>();
        for (CategoryEntity categoryEntity : categoryEntities) {
            if(parentCategory.getCatId().equals(categoryEntity.getParentCid())){
                SelectCategoryListWithTreeResponse response = new SelectCategoryListWithTreeResponse();
                BeanUtils.copyProperties(categoryEntity, response);
                // 修复：为null的sort字段设置默认值
                if (response.getSort() == null) {
                    response.setSort(0);
                }
                queryChildren(response, categoryEntities);
                children.add(response);
            }
        }
        if(CollectionUtil.isNotEmpty(children)){
            children.sort(Comparator.comparingInt(SelectCategoryListWithTreeResponse::getSort));
        }
        parentCategory.setChildren(children);
    }

}